package com.chixing.controller;


import com.alipay.api.domain.AlipayEbppInvoiceListExpenseSyncModel;
import com.chixing.pojo.EsJobCompany;
import com.chixing.service.EsJobService;
import com.chixing.service.IJobDetailService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.*;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class EsJobDetialController {

    @Autowired
    private EsJobService esJobService;

    @Autowired
    private ElasticsearchRestTemplate restTemplate;
    @Autowired
    private IJobDetailService jobDetailService;

    @GetMapping("saveJobComany")
    public String saveJobComany(){
        List<EsJobCompany> esJobCompanyList = jobDetailService.getJobCompany();
        Iterable<EsJobCompany> esJobCompanyLists = esJobService.saveAll(esJobCompanyList);
        return "sava successfully";
    }

    //根据名字查询
    @GetMapping("getByName/{name}/{pageNum}")
    public List<EsJobCompany> getByName(@PathVariable("name") String jobName,@PathVariable("pageNum")Integer pageNum){
        return esJobService.findByjobName(jobName);
    }

    //分页查询
    @GetMapping("getAllPage")
    public Page<EsJobCompany> getAllPage(){
        Pageable page = PageRequest.of(0,10,Sort.Direction.ASC,"jobId");
        Page<EsJobCompany> allData = esJobService.findAll(page);
        System.out.println("getAllPage : " + allData);
        return  allData;
    }



    /*public List<EsJobCompany> getHighByJobComany(@PathVariable("kw") String  kw){
        System.out.println("kw = " + kw);
        //根据一个值查询多个字段，并高亮显示，这里的查询是取并集，
        //即多个字段只要有一个字段满足即可
        //需要查询的字段
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
                .should(QueryBuilders.matchQuery("jobName",kw))
                .should(QueryBuilders.matchQuery("jobType",kw))
                .should(QueryBuilders.matchQuery("jobDegree",kw))
                .should(QueryBuilders.matchQuery("jobExperience",kw))
                .should(QueryBuilders.matchQuery("companyName",kw))
                .should(QueryBuilders.matchQuery("companyIndustry",kw));

        //构建高亮查询
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(boolQueryBuilder)
                .withHighlightFields(
                        new HighlightBuilder.Field("jobName"),
                        new HighlightBuilder.Field("jobType"),
                        new HighlightBuilder.Field("jobDegree"),
                        new HighlightBuilder.Field("jobExperience"),
                        new HighlightBuilder.Field("companyName"),
                        new HighlightBuilder.Field("companyIndustry"))
                .withHighlightBuilder(new HighlightBuilder()
                        .preTags("<span style ='color:black'>")
                        .postTags("</span>"))
                .build();

        //查询
        SearchHits<EsJobCompany> search = restTemplate.search(searchQuery, EsJobCompany.class);

        //得到查询返回的内容
        List<SearchHit<EsJobCompany>> searchHitList = search.getSearchHits();

        //设置设置一个最后需要返回的实体类集合
        List<EsJobCompany> esJobCompanyList = new ArrayList<>();
        for (SearchHit<EsJobCompany> searchHit:searchHitList){
            //高亮内容
            Map<String,List<String>> highlightFields = searchHit.getHighlightFields();

            //将高亮内容填充到content中
            String jobName = highlightFields.get("jobName") == null ?searchHit.getContent().getJobName() :highlightFields.get("jobName").get(0);
            String jobType = highlightFields.get("jobType") == null ?searchHit.getContent().getJobName() :highlightFields.get("jobType").get(0);
            String jobDegree = highlightFields.get("jobDegree") == null ?searchHit.getContent().getJobName() :highlightFields.get("jobDegree").get(0);
            String jobExperience = highlightFields.get("jobExperience") == null ?searchHit.getContent().getJobName() :highlightFields.get("jobExperience").get(0);
            String companyName = highlightFields.get("companyName") == null ?searchHit.getContent().getJobName() :highlightFields.get("companyName").get(0);
            String companyIndustry = highlightFields.get("companyIndustry") == null ?searchHit.getContent().getJobName() :highlightFields.get("companyIndustry").get(0);
            searchHit.getContent().setJobName(jobName);
            searchHit.getContent().setJobType(jobType);
            searchHit.getContent().setJobDegree(jobDegree);
            searchHit.getContent().setJobExperience(jobExperience);
            searchHit.getContent().setCompanyName(companyName);
            searchHit.getContent().setCompanyIndustry(companyIndustry);

            //放到实体类中
            esJobCompanyList.add(searchHit.getContent());
        }
        System.out.println("搜素集合: " + esJobCompanyList);
        return esJobCompanyList;

    }*/
//查询高亮数据
    @GetMapping("getHighByJobComany/{kw}/{pageNum}")
    public Map<String,Object> getHighByJobComanyByPage(@PathVariable("kw")String kw, @PathVariable("pageNum")Integer pageNum) {
        if (pageNum == null) {
            pageNum = 1;
        }
        Pageable pageable = PageRequest.of(pageNum - 1, 7);
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if (kw != null) {
            QueryBuilder queryBuilder = QueryBuilders.queryStringQuery(kw);
            boolQueryBuilder.must(queryBuilder);
        }


        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        NativeSearchQuery query = builder
                .withQuery(boolQueryBuilder)
                .withPageable(pageable)
                .withHighlightFields(
                        new HighlightBuilder.Field("jobName"))
//                .withHighlightBuilder(new HighlightBuilder()
//                        .preTags("<span style='color:red'")
//                        .postTags("</span>"))
                .build();
        SearchHits<EsJobCompany> search = restTemplate.search(query, EsJobCompany.class);
        List<EsJobCompany> esJobCompanyList = new ArrayList<>();
        for (SearchHit<EsJobCompany> searchHit : search) {
            //高亮内容
            Map<String, List<String>> highlightFields = searchHit.getHighlightFields();

            //将高亮内容填充到content中
            String highlightJobName = highlightFields.get("jobName") == null ? searchHit.getContent().getJobName() : highlightFields.get("jobName").get(0);

            searchHit.getContent().setJobName(highlightJobName);


            //放到实体类中
            esJobCompanyList.add(searchHit.getContent());
        }
        SearchPage<EsJobCompany> searchPage = SearchHitSupport.searchPageFor(search, query.getPageable());
        //总记录数
        long totalElements = searchPage.getTotalPages();
        //总页数
        int totalPages = searchPage.getTotalPages();
        //当前页
        int currentPages = searchPage.getPageable().getPageNumber();
        System.out.println("==============="+currentPages+"==================");
        Map<String, Object> map = new HashMap<>();
        map.put("esJobCompany", esJobCompanyList);
        map.put("totalElements", totalElements);
        map.put("totalPages", totalPages);
        map.put("currentPage", currentPages);
        map.put("kw", kw);
        return map;
    }

//    @GetMapping("getHighByJobComany/{kw}")
//    public Map<String,Object> getHighByJobComanytotal(@PathVariable("kw")String kw, Integer pageNum,String jobName) {
//        if (pageNum == null) {
//            pageNum = 1;
//        }
//        Pageable pageable = PageRequest.of(pageNum - 1, 7);
//        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
//        if (jobName != null) {
//            QueryBuilder queryBuilder = QueryBuilders.queryStringQuery(jobName);
//            boolQueryBuilder.must(queryBuilder);
//        }
//
////        SortBuilder sortBuilder = SortBuilders.scoreSort();
////        FieldSortBuilder jobId = SortBuilders.fieldSort("jobId");
////        sortBuilder.order(SortOrder.DESC);
//
//        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
//        NativeSearchQuery query = builder
//                .withQuery(boolQueryBuilder)
//                .withPageable(pageable)
//                .withHighlightFields(
//                        new HighlightBuilder.Field("jobName"))
//                .withHighlightBuilder(new HighlightBuilder()
//                        .preTags("<span style='color:black'")
//                        .postTags("</span>"))
//                .build();
//        SearchHits<EsJobCompany> search = restTemplate.search(query, EsJobCompany.class);
//        List<EsJobCompany> esJobCompanyList = new ArrayList<>();
//        for (SearchHit<EsJobCompany> searchHit : search) {
//            //高亮内容
//            Map<String, List<String>> highlightFields = searchHit.getHighlightFields();
//
//            //将高亮内容填充到content中
//            String highlightJobName = highlightFields.get("jobName") == null ? searchHit.getContent().getJobName() : highlightFields.get("jobName").get(0);
//
//            searchHit.getContent().setJobName(highlightJobName);
//
//
//            //放到实体类中
//            esJobCompanyList.add(searchHit.getContent());
//        }
//        SearchPage<EsJobCompany> searchPage = SearchHitSupport.searchPageFor(search, query.getPageable());
//        //总记录数
//        long totalElements = searchPage.getTotalPages();
//        //总页数
//        int totalPages = searchPage.getTotalPages();
//        //当前页
//        int currentPages = searchPage.getPageable().getPageNumber();
//        System.out.println("==============="+currentPages+"==================");
//        Map<String, Object> map = new HashMap<>();
//
//        map.put("esJobCompany", esJobCompanyList);
//        map.put("totalElements", totalElements);
//        map.put("totalPages", totalPages);
//        map.put("currentPage", currentPages);
//        map.put("kw", kw);
//        map.put("num",esJobCompanyList.size());
//        return map;
//    }
}

